import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;
import java.util.HashMap;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String rememberMe = request.getParameter("rememberMe");

        ServletContext context = getServletContext();
        if (context.getAttribute("userMap") == null) {
            request.setAttribute("msg", "当前用户未注册");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
        } else {
            HashMap<String, String> usermap = (HashMap<String, String>) context.getAttribute("userMap");
            if (usermap.containsKey(username)) {
                if (usermap.get(username).equals(password)) {
                    if ("yes".equals(rememberMe)) {
                        Cookie usernameCookie = new Cookie("username", username);
                        Cookie passwordCookie = new Cookie("password", password);
                        usernameCookie.setMaxAge(60 * 60 * 24 * 7);
                        passwordCookie.setMaxAge(60 * 60 * 24 * 7);
                        response.addCookie(usernameCookie);
                        response.addCookie(passwordCookie);
                    }
                    HttpSession session = request.getSession();
                    session.setAttribute("username", username);
                    response.sendRedirect(request.getContextPath() + "/home.jsp");
                } else {
                    request.setAttribute("msg", "用户名或密码错误");
                    request.getRequestDispatcher("/login.jsp").forward(request, response);
                }
            } else {
                request.setAttribute("msg", "当前用户名未注册");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            }

        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);


    }
}